package com.cy.deepseeksport.service.search;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.cy.deepseeksport.NLP.ParseWebSearchResponse.buildAnalysisEntry;

@Component
public class BochaApiClient {

    private static final String API_ENDPOINT = "https://api.bochaai.com/v1/ai-search";

    private final RestTemplate restTemplate;
    private final String apiKey;

    @Autowired
    public BochaApiClient(
            RestTemplateBuilder restTemplateBuilder,
            @Value("${deepseek.search-api-key}") String apiKey) {
        this.restTemplate = restTemplateBuilder.build();
        this.apiKey = apiKey;
    }

    public String search(String query,
                                      String freshness,
                                      Integer count,
                                      Boolean answer,
                                      Boolean stream) {

        // 构建请求体（使用LinkedHashMap保持参数顺序）
        Map<String, Object> requestBody = new LinkedHashMap<>();
        requestBody.put("query", query);       // 唯一变量
        requestBody.put("freshness", "noLimit");
        requestBody.put("count", 50);
        requestBody.put("answer", false);
        requestBody.put("stream", false);

// 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.set("Accept", "*/*");
        headers.set("Content-Type", "application/json");
        headers.set("Connection", "keep-alive");

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

// 发送请求
        ResponseEntity<BochaApiResponse> exchange = restTemplate.exchange(
                API_ENDPOINT,
                HttpMethod.POST,
                entity,
                BochaApiResponse.class
        );



        BochaApiResponse body = exchange.getBody();

        StringBuilder analysisData = new StringBuilder();
        analysisData.append("=== 网络信息分析数据集 ===\n\n");

        for (BochaApiResponse.Message message : body.getMessages()) {

            String content = message.getContent();

            if (message.getContentType().equals("webpage")) {
                JSONObject respJson = JSON.parseObject(content, JSONObject.class);

                JSONArray news = respJson.getJSONArray("value");
                try{
                    for (int i = 0; i < news.size(); i++) {
                        try {
                            JSONObject item = news.getJSONObject(i);
                            analysisData.append(buildAnalysisEntry(item)).append("\n\n");
                        } catch (Exception e) {
                            System.err.println("解析第 " + (i+1) + " 条数据失败: " + e.getMessage());
                        }
                    }
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
            }

        }

       return analysisData.toString();



        //return response.getBody();
    }
}